package com.liit.upload;

import java.io.File;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

import com.liit.exception.ParameterException;
import com.liit.util.PropertiesUtils;

/**
 * 
 * @author dingweibo
 * @Title: UploadUtil.java
 * @Description: 上传文件工具类
 * @date 2016年6月2日
 */
public class UploadUtil {

	// 默认路径
	public static final String UPLOAD_PATH = PropertiesUtils.findPropertiesKey("file.upload.path");
	public static final String[] TYPE_IMAGES = { "GIF", "JPEG", "PNG", "JPG", "BMP" };

	/**
	 * 保存文件到磁盘
	 * 
	 * @param file
	 * @param path
	 *            文件路径(不包含文件名)
	 * @param fileName
	 *            文件名
	 */
	public static void uploadFile(MultipartFile file, String path, String fileName) {
		try {
			File f = new File(path, fileName);
			if (!f.exists()) {
				f.mkdirs();
			}
			file.transferTo(f);
		} catch (Exception e) {
			throw new RuntimeException("file save error", e);
		}
	}

	/**
	 * 保存文件到磁盘
	 * 
	 * @param files
	 *            文件名是map的key
	 * 
	 * @param path
	 *            文件路径(不包含文件名)
	 */
	public static void uploadFile(Map<String, MultipartFile> files, String path) {
		if (files == null || files.isEmpty()) {
			return;
		}
		for (String fileName : files.keySet()) {
			uploadFile(files.get(fileName), path, fileName);
		}
	}

	/**
	 * 上传图片
	 * 
	 * @param file
	 * @param path
	 *            文件路径(不包含文件名)
	 * @param fileName
	 *            文件名
	 */
	public static void uploadImage(MultipartFile file, String path, String fileName) {
		boolean isTrue = false;
		for (String type : TYPE_IMAGES) {
			if (fileName.toUpperCase().endsWith(type)) {
				isTrue = true;
				break;
			}
		}
		if (!isTrue) {
			throw new ParameterException("File error,please upload image file.");
		}
		uploadFile(file, path, fileName);
	}

	/**
	 * 上传图片
	 * 
	 * @param files
	 *            文件名是map的key
	 * 
	 * @param path
	 *            文件路径(不包含文件名)
	 */
	public static void uploadImage(Map<String, MultipartFile> files, String path) {
		if (files == null || files.isEmpty()) {
			return;
		}
		for (String fileName : files.keySet()) {
			uploadImage(files.get(fileName), path, fileName);
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 * @param fileName
	 * @return
	 */
	public static boolean deleteFile(String path, String fileName) {
		File f = new File(path, fileName);
		if (f.isFile() && f.exists()) {
			return f.delete();
		}
		return false;
	}
}